package com.example.reagent_management.ui.message

import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.example.lib_base.base.BaseDBFragment
import com.example.lib_base.base.DataBindingConfig
import com.example.lib_base.event.ShareViewModel
import com.example.lib_base.utils.onQueryTextFlow
import com.example.reagent_management.BR
import com.example.reagent_management.R
import com.example.reagent_management.databinding.FragmentMessageBinding
import com.example.reagent_management.ui.activity.MainActivityKt
import com.example.reagent_management.ui.message.adpter.MessageAdapter
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

@AndroidEntryPoint
class MessageFragment : BaseDBFragment() {

    private val mState: MessageViewModel by viewModels()
    private lateinit var mEvent: ShareViewModel
    private var filter = ""
    private lateinit var job: Job

    override fun getDataBindingConfig(): DataBindingConfig {
        val adapter = MessageAdapter()
        job = mState.getAllMessage("")
        mState.allMessage.observe(this@MessageFragment, Observer {
            lifecycleScope.launch {
                adapter.submitData(it)
                Log.e("allMessage", "getDataBindingConfig: ${adapter.itemCount}")
            }
        })
        return DataBindingConfig(R.layout.fragment_message)
            .addBindingParam(BR.adapter, adapter)
    }

    override fun initViewModel() {
        mEvent = getApplicationScopeViewModel(ShareViewModel::class.java)
    }

    override fun initViewOrObserve() {
        with(binding as FragmentMessageBinding) {
            setHasOptionsMenu(true)
            (activity as MainActivityKt).setSupportActionBar(toolbar)

            toolbar.setNavigationOnClickListener {
                nav().navigateUp()
            }
            mState.changeState.observe(this@MessageFragment, Observer {
                if (it != null) {
                    if (it != 0) {
//                        if (job.isActive) job.cancel()
//                        if (job.isCancelled) {
                            job = mState.getAllMessage(filter)

//                        }
                    }
                }
            })
        }
    }

    //TODO
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.temp -> {
                //Write here what to do you on click
                filter = "温度"
                mState.changeState.value = 1
                return true
            }
            R.id.hub -> {
                filter = "湿度"
                mState.changeState.value = 1
                return true
            }
            R.id.day -> {
                filter = "到期时间"
                mState.changeState.value = 1
                return true
            }
            R.id.count -> {
                filter = "库存剩余"
                mState.changeState.value = 1
                return true
            }
            R.id.deleteRemind -> {
                mState.deleteALlMessage()
                return true
            }

        }
        return super.onOptionsItemSelected(item)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.menu_remind, menu)
        val findItem = menu.findItem(R.id.search)
        val mSearchView = (findItem.actionView) as SearchView
        // 去掉搜索框默认的下划线
//        val searchPlate = mSearchView.findViewById<View>(R.id.search_plate)
//        val submitArea = mSearchView.findViewById<View>(R.id.submit_area)
//        searchPlate.background = null
//        submitArea.background = null
        // 设置搜索框背景样式
//        val mSearchSrcTextView =
//            mSearchView.findViewById<SearchView.SearchAutoComplete>(R.id.search_src_text)
//        mSearchSrcTextView.hint = "输入查询相关信息"
//        mSearchSrcTextView.background = getDrawable(requireContext(), R.drawable.seach_toolbar)
        lifecycleScope.launch {
            mSearchView.onQueryTextFlow()
                .debounce(500)
//                .filter { it.isNotEmpty() }
                .distinctUntilChanged()
                .flowOn(Dispatchers.IO)
                .collect {
//                    if (job.isActive) job.cancel()
//                    if (job.isCancelled) {
                        job = mState.getAllMessage(it)
//                    }
                }
        }
    }

    override fun onDestroyView() {
        mState.changeState.value = 0
        //清楚红点，在本页面时表示已看完更新的数据
        mEvent.messageRemind.value = 0
        //不加将内存泄露
        (activity as MainActivityKt).setSupportActionBar(null)
        super.onDestroyView()
    }



}